﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using MicropleSoft.Common.Library;
using MicropleSoft.WmsServiceLibrary.Base;
using MicropleSoft.WmsServiceLibrary.Domain;
using MicropleSoft.WmsServiceLibrary.ServiceFactory;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MicropleSoft.WmsServiceLibrary.DataSets
{
    public class DataTablePersist : BaseService, IDataTablePersist
    {
        private const string UpdateCommonFieldValue = ", UPDATED_BY =@UPDATED_BY,UPDATED_DATE=@UPDATED_DATE";
        private const string InsertCommonField = " ,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE ";
        private const string InsertCommonValue = " ,@CREATED_BY,@CREATED_DATE,@UPDATED_BY,@UPDATED_DATE ";
        private const string InsertSql = "insert into {0} ( {1} ) values( {2} )";
        private const string UpdateSql = "update  {0}  {1} where {2}";
        private const string DeleteSql = "delete from  {0}  where {1}";
        private Database db = ServiceFactoryCreator.CreateAbstractServiceFactory().CreateDatabase();
        public void SaveDataTable(List<ItemTemplate> itemTemplates, DataTable dataTable, string dataTableName, List<MicropleSoft.Common.Library.EntityKey> entityKeys)
        {

            var q = itemTemplates.Select(it => it.ColumnName);

            //执行构造insert语句
            string insertFields = MicropleSoft.Common.Library.StringUtil.Concat(q, ",");
            string insertValues = MicropleSoft.Common.Library.StringUtil.Concat(q, ",@");
            insertValues = "@" + insertValues;

            //新增语句
            string insertCommandSql = string.Format(InsertSql, dataTableName, insertFields + InsertCommonField, insertValues + InsertCommonValue);

            //执行构造update语句
            var updateValues = new List<string>() ;
            foreach (var itemTemplete in itemTemplates)
            {
                if (entityKeys.Where(ek=>String.Compare( ek.PrimaryKeyName , itemTemplete.ColumnName,true)==0).Count() >0)
                    continue;
                updateValues .Add(   itemTemplete.ColumnName + " = @" + itemTemplete.ColumnName  );
            }
            var updateValueList = MicropleSoft.Common.Library.StringUtil.Concat(updateValues, " , ");
            updateValueList = " SET " + updateValueList + UpdateCommonFieldValue;

            var conditions = new List<String>();
            foreach (var entityKey in entityKeys)
            {
                conditions.Add( entityKey.PrimaryKeyName + " = @" + entityKey.PrimaryKeyName);
            }
            var conditionsConcat = MicropleSoft.Common.Library.StringUtil.Concat(conditions, " and ");

            //修改语句
            string updateCommandSql = string.Format(UpdateSql, dataTableName, updateValueList, conditionsConcat);

            //删除语句
            string deleteCommandSql = string.Format(DeleteSql, dataTableName,  conditionsConcat);

            DbCommand insertCommand = db.GetSqlStringCommand(insertCommandSql);
            DbCommand updateCommand = db.GetSqlStringCommand(updateCommandSql);
            DbCommand deleteCommand = db.GetSqlStringCommand(deleteCommandSql);

            foreach (var itemTemplate in itemTemplates)
            {
                DbType dbType = DbType.Int32;
                //COLUMN_TYPE INT,/*数据库字段类型：1-varchar,2-int,3-datatime,4- number，5-布尔类型（实际使用int类型0表示否1表示是）*/
                switch (itemTemplate.DataType)
                {
                    case ConstFlags.ColumnType4Varchar:
                        dbType = DbType.String;
                        break;
                    case ConstFlags.ColumnType4Int:
                        dbType = DbType.Int32;
                        break;
                    case ConstFlags.ColumnType4DateTime:
                        dbType = DbType.DateTime;
                        break;
                    case ConstFlags.ColumnType4Number:
                        dbType = DbType.Decimal;
                        break;
                    case ConstFlags.ColumnType4Bool:
                        dbType = DbType.Int32;
                        break;
                    default:
                        dbType = DbType.String;
                        break;
                }

                db.AddInParameter(insertCommand, itemTemplate.ColumnName, dbType, itemTemplate.ColumnName,
                                  DataRowVersion.Current);
                db.AddInParameter(updateCommand, itemTemplate.ColumnName, dbType, itemTemplate.ColumnName,
                                  DataRowVersion.Current);

                if (entityKeys.Where(ek => String.Compare(ek.PrimaryKeyName, itemTemplate.ColumnName, true) == 0).Count() >
                    0)
                {
                    db.AddInParameter(deleteCommand, itemTemplate.ColumnName, dbType, itemTemplate.ColumnName,
                               DataRowVersion.Original);
                }
            }

            //插入Common字段参数
            //insert
            db.AddInParameter(insertCommand, "CREATED_BY", DbType.String, base.GetUserId());
            db.AddInParameter(insertCommand, "CREATED_DATE", DbType.DateTime, DateTime.Now);
            db.AddInParameter(insertCommand, "UPDATED_BY", DbType.String, base.GetUserId());
            db.AddInParameter(insertCommand, "UPDATED_DATE", DbType.DateTime, DateTime.Now);
            //update
            db.AddInParameter(updateCommand, "UPDATED_BY", DbType.String, base.GetUserId());
            db.AddInParameter(updateCommand, "UPDATED_DATE", DbType.DateTime, DateTime.Now);

            var ds = new DataSet();
            dataTable.TableName = dataTableName;
            ds.Tables.Add(dataTable);
            db.UpdateDataSet(ds, dataTableName, insertCommand, updateCommand, deleteCommand, UpdateBehavior.Transactional);

        }
    }
}
